﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConvergentSeries
{
    class ConvergentSeries
    {
        public delegate double ElementGeneratorDelegate(int n);

        public static double CalculateSum(ElementGeneratorDelegate getElement)
        {
            double sum = 0;
            double currentElement = getElement(0);
            double prevElement = currentElement + 1;
            for (int i = 1; Math.Abs(prevElement) - Math.Abs(currentElement) > 0.0000001; i++)
            {
                sum += currentElement;
                prevElement = currentElement;
                currentElement = getElement(i);
            }
            return sum;
        }

        public static double Seq1(int i)
        {
            return 1 / Math.Pow(2, i);
        }

        public static double Seq2(int i)
        {
            i++;
            double result = 1;
            while (i > 0)
            {
                result /= i;
                i--;
            }
            return result;
        }

        public static double Seq3(int i)
        {
            if (i == 0)
            {
                return 1;
            }
            return Math.Pow(0.5, i) * (((i & 1) == 0) ? -1 : 1);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("{0:F2}", CalculateSum(Seq1));
            Console.WriteLine("{0:F2}", CalculateSum(Seq2));
            Console.WriteLine("{0:F2}", CalculateSum(Seq3));
        }
    }
}
